<template>
  <el-form ref="form" label-width="80px" size="small" style="margin-top: 2%; margin-left: 1%">
    <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openadd()">新增</el-button>
    <template>
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column label="表头" prop="headerName" align="center">
          <template #default="scope">
            {{ scope.row.data }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['system:config:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="deleteById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <el-dialog ref="form" :title="title" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="tableHeader" label-width="80px" size="mini">
        <el-form-item prop="headShit" label="资料名称">
          <el-select v-model="header" value-key="id" placeholder="请选择表头" style="width: 250px">
            <el-option v-for="option in dropdownOptions" :key="option.id" :value="option" :label="option.name" />
          </el-select>
        </el-form-item>
        <el-form-item style="margin-left: 15%">
          <el-button type="primary" @click="add_header">提交</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-form>
</template>

<script>
import { page_id } from '@/api/files_1.js'
import { add, page, deleteById } from '@/api/docu_filter.js'
import { parseTime } from '@/utils'
import { mapState, mapMutations } from 'vuex'

export default {
  data() {
    return {
      input1: '',
      input2: '',
      tableHeader: {
        headerId: undefined,
        headerKey: undefined,
        type: undefined,
        docuId: null
      },
      header: {},
      loading: false,
      background: true,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      queryParams: {
        status: '',
        createTime: '',
        // 添加开始时间字段
        endTime: ''
      },
      entryDate: [],
      // 用于 v-model 绑定日期选择器的值
      value: {},
      createTime: '',
      endTime: '',
      title: '',
      // 被选中的 id 数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      tableKey: 0,
      list: null,
      total: 0,
      dropdownOptions: []
    }
  },
  computed: {
    ...mapState(['name'])
  },
  mounted() {
    this.zlId = this.$route.params.id
    this.page()
  },
  methods: {
    onSubmit() {
      this.page()
    },
    // 查询分页数据
    page() {
      const requestData = {
        current: this.current,
        pageSize: this.pageSize
      }
      page(this.zlId, requestData)
        .then((res) => {
          if (res.code === 1) {
            this.totalCount = res.data.total
            this.tableData = res.data.records
          } else {
            console.error('API 请求未成功，响应码：', res.code)
          }
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    // 表单重置
    reset() {
      this.tableHeader = {}
      this.header = {}
    },
    openadd(row) {
      this.reset()
      this.dialogVisible = true
      this.title = '新增筛选表头'
      this.fetchDropdownOptions()
    },
    // 重置方法
    clear() {
      this.queryParams.status = ''
      this.entryDate = []
      this.page()
    },
    // 添加数据
    add_header() {
      // 检查输入是否为空
      if (!this.header) {
        this.$message.error('表头不能为空')
        return
      }

      const dataToSend = {
        docuId: this.header.docuId,
        headerId: this.header.id,
        headerKey: this.header.headerKey,
        data: this.header.name
      }

      add(dataToSend).then((resp) => {
        if (resp.code == '1') {
          this.dialogVisible = false
          this.$message({ message: '保存成功', type: 'success' })
          // 重新获取数据而不是直接修改本地数组
          this.page()
          // 重置表单
          this.reset()
        } else {
          // 根据后端返回的错误信息进行提示
          if (resp.msg === '名称已存在') {
            this.$message.error('表头已存在，请重新输入')
          } else {
            this.$message.error(resp.msg)
          }
        }
      })
    },
    /* preview() {
      // 1. 打开窗口
      this.dialogVisible4 = true;
      // 对数组进行排序
      this.tableData.sort((a, b) => a.sequence - b.sequence);
      // 显示预览弹框
      this.dialogVisible4 = true;
    }, */
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteById(id).then((resp) => {
            if (resp.code == '1') {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },
    ...mapMutations('schoolmanage', ['getname']),
    formatJson(filterVal) {
      return this.list.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 新增方法：获取下拉选项数据
    fetchDropdownOptions() {
      // 使用后端接口获取数据并提取 name 属性作为下拉选项
      page_id(this.zlId)
        .then((response) => {
          if (response.code === 1) {
            this.dropdownOptions = response.data
          } else {
            console.error('获取下拉选项数据失败')
          }
        })
        .catch((error) => {
          console.error('Error fetching dropdown options:', error)
        })
    }
  }
}
</script>

<style scoped>
/* 全局 CSS 或者在<style scoped>内 */
.el-form-item.is-disabled.el-input__inner,
.is-disabled.el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
</style>
